<!-- CollapseItem.svelte-->
<script lang="ts">
	import { getContext } from 'svelte';
	import ArrowRight from '$lib/assets/icons/symbol/arrow-right.svg?component'

	// 声明子组件props
	const {
		children,
		titleSlot,
		name,
		title,
		disabled = false
	} = $props<{
		children?: any;
		titleSlot?: any;
		name: string;
		title: string | number | boolean | null | undefined | HTMLElement;
		disabled?: boolean;
	}>();

	// 获取父组件提供的上下文
	const collapse = getContext<{
		activeNames: () => string[];
		handleItemClick: (name: string) => void;
	}>('collapse');

	if (!collapse) {
		throw new Error('CollapseItem must be used inside Collapse');
	}

	// 响应式状态管理
	let isActive = $state(false);

	// 当激活状态变化时更新
	$effect(() => {
		isActive = collapse.activeNames().includes(name);
	});

	// 处理标题点击
	function handleClick() {
		if (disabled) return;
		collapse.handleItemClick(name);
	}
</script>

<div class="s-collapse-item">
	<div
		class={`s-collapse-item__header hover-bg ${isActive ? 'is-active' : ''} ${disabled ? 'is-disabled' : ''}`}
		onclick={handleClick}
		onkeydown={() => {}}
		role="button"
		tabindex="0"
	>
		{#if titleSlot && typeof titleSlot === 'function'}
			{@render titleSlot?.()}
		{:else}
			<span>{title}</span>
		{/if}
		<div class={`s-collapse-item__arrow ${isActive ? 'is-active' : ''}`}>
			<ArrowRight width="22" height="22"></ArrowRight>
		</div>
	</div>

	<!-- 内容区域带平滑过渡动画 -->
	<div class={`s-collapse-item__content ${isActive ? 'is-active' : ''}`}>
		<div class="s-collapse-item__content__wrap">
			{@render children?.()}
		</div>
	</div>
</div>

<style>
	.s-collapse-item {
		border-bottom: var(--border);
	}

	.s-collapse-item:last-child {
		border-bottom: none;
	}

	.s-collapse-item__header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 12px 16px;
		cursor: pointer;
		transition: background-color 0.2s;
	}

	.s-collapse-item__header:hover.is-disabled {
		background-color: none;
	}

	.s-collapse-item__header.is-disabled {
		cursor: not-allowed;
		opacity: 0.6;
	}

	.s-collapse-item__header__title {
		flex: 1;
	}

	.s-collapse-item__arrow {
		display: flex;
		transition: transform 0.2s ease;
	}

	.s-collapse-item__arrow.is-active {
		transform: rotate(90deg);
	}

	.s-collapse-item__content {
		display: grid;
		grid-template-rows: 0fr;
		transition: grid-template-rows 0.2s ease-in-out;
	}

	.s-collapse-item__content.is-active {
		grid-template-rows: 1fr;
	}

	.s-collapse-item__content__wrap {
		overflow: hidden;
	}
</style>
